package com.mt.api.modules.service.impl;

import com.alibaba.fastjson.JSON;
import com.mt.common.exception.BadRequestException;
import com.mt.common.utils.FileUtil;
import com.mt.common.response.WebResponse;
import com.mt.common.response.WebResponseUtils;
import com.mt.api.modules.domain.ToolQiniuConfig;
import com.mt.api.modules.service.IAppUploadService;
import com.mt.api.util.QiNiuUtil;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: plover
 * @Date: 2021/12/31 5:03 下午
 * @Description:
 */
@Slf4j
@Service
public class AppUploadServiceImpl implements IAppUploadService {

    @Value("${qiniu.max-size}")
    private Long maxSize;

    @Override
    public WebResponse picUpload(MultipartFile file) {
        FileUtil.checkSize(maxSize, file.getSize());
        //TODO 改为查数据库
        ToolQiniuConfig qiniuConfig = new ToolQiniuConfig();
        qiniuConfig.setId(1L);
        qiniuConfig.setAccessKey("I80Yjtyh2EZ0SOc7c2roYjymt94LXBVeyMdYmSbl");
        qiniuConfig.setBucket("mat");
        qiniuConfig.setHost("http://img.matforever.cn");
        qiniuConfig.setSecretKey("WkHlWfLop4Hr9oXvIDtuzG-VpXLDQX5--R_xjZym");
        qiniuConfig.setType("公开");
        qiniuConfig.setZone("华东");

        if (qiniuConfig.getId() == null) {
            throw new BadRequestException("请先添加相应配置，再操作");
        }

        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(qiniuConfig.getZone()));
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        String upToken = auth.uploadToken(qiniuConfig.getBucket());
        try {
            String key = "image/" + RandomStringUtils.random(4, true, false) + file.hashCode();
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            String picUrl = qiniuConfig.getHost() + "/" + putRet.key;
            return WebResponseUtils.success(picUrl);
        } catch (Exception e) {
            log.error("picUpload error", e);
            throw new BadRequestException(e.getMessage());
        }
    }
}
